% Code generates robustness check in Table A3:  No inattention in preference estimates


%% 0) import data inc set specification for preferences
clear; clc;
pref_spec=2; % run for  2
close all;
rng(88);

% import bootstrap weights
%---------------------------
w_expost = csvread('../Data/created_data/xp_w.csv', 0,0);

% import and setup expost data
%-----------------------------
[xpdata,n_prefparms,n_groomchars] = import_and_setup_expost(pref_spec);

%% 1) Estimate preferences
% set starting values 
%--------------------
% errors
ST_sigma_ep=2;% combined error

beta_start=0.1*ones(n_prefparms,1)'; % pref parms
p_starting_vals(1)=ST_sigma_ep;
i=1+size(beta_start,2);
p_starting_vals(2:i)=beta_start;
p_starting_vals(i+1)=0.2; % inattention share
lb=-10.*ones(size(p_starting_vals))
ub=Inf.*ones(size(p_starting_vals))

w=ones(size(xpdata.EP_choice));

% impose constraint (no inattention): 
lb(end)=0
ub(end)=0
p_starting_vals(end)=0

% estimate preferences
options_f = optimoptions('fmincon', 'UseParallel', false, 'MaxIterations', 1e6, 'CheckGradients', false, 'MaxFunEvals', 1000000, ...
    'SpecifyObjectiveGradient', false, 'OptimalityTolerance', 1e-6, 'SpecifyConstraintGradient',false, 'FiniteDifferenceType',  'forward');

 [pref_estimates_rob,ll,~,~,lambda,grad,H] = fmincon(@(alpha0) pref_mom(xpdata,n_prefparms,alpha0,w), ...
                    p_starting_vals, [], [], [], [],lb,ub, [], options_f);
 
%% 2) Bootstrap preferences
N=500;
bs_prefs=ones(size(p_starting_vals',1),N);

parfor n=0:N 
                n
                w=w_expost(:,n+1);
                [temp,ll,~,~,lambda,grad,H] = fmincon(@(alpha0) pref_mom(xpdata,n_prefparms,alpha0,w), ...
                            p_starting_vals, [], [], [], [],lb,ub, [], options_f);
                bs_prefs(:,n+1)=[temp'];
end

se= std(bs_prefs(:,2:end),0,2);       
real=bs_prefs(:,1);
t=real./se;

pref_results=[real se t]
colNames = {'coef','se','t'}
sTable = array2table(pref_results,'VariableNames',colNames) 

% TABLE A3
%--------------------------------------------------------------------------
writetable(sTable,'../Output_New/bs_results/table_prefs_robust.xlsx')

